package com.book.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.book.dao.AddressDao;
import com.book.dao.OrderDao;
import com.book.entity.Address;
import com.book.entity.Order;
import com.book.service.AddressService;
import com.book.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AddressServiceImpl implements AddressService {
    @Autowired
    private AddressDao addressDao;
    @Autowired
    private OrderDao orderDao;

    @Override
    public ResponseResult getAddressAll(String userId) {
        try {
            QueryWrapper<Address> qw = new QueryWrapper<>();
            qw.eq("user_id",userId);
            return new ResponseResult(200,"获取地址成功",addressDao.selectList(qw));
        }catch (Exception e){
            return new ResponseResult(3001,"获取地址失败，请刷新页面");
        }
    }

    @Override
    public ResponseResult addAddress(Address address) {
        try {
            addressDao.insert(address);
            return new ResponseResult(200,"添加成功");
        }catch (Exception e){
            return new ResponseResult(3002,"添加失败："+e.getMessage());
        }
    }

    /**
     *
     * @param id 被删除的地址的id
     * @return
     */
    @Override
    public ResponseResult deleteAddressById(int id) {
        try {
            addressDao.deleteById(id);
            return new ResponseResult(200,"删除地址成功");
        }catch (Exception e){
            e.getStackTrace();
            return new ResponseResult(3003,"删除地址失败");
        }
    }

    @Override
    public ResponseResult getAddressById(int id) {
        try {
            return new ResponseResult(200,"查询此地址成功",addressDao.selectById(id));
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseResult(3004,"获取此地址信息失败!!!");
        }
    }

    /**
     *
     * @param address
     * @return
     */
    @Override
    public ResponseResult editAddress(Address address) {
        try {
            QueryWrapper<Order> qw = new QueryWrapper<>();
            qw.eq("address_id",address.getId()).eq("status",1);//判断订单表中是否有未完成的订单应用了该地址
            if(orderDao.selectList(qw).size() != 0){
                return new ResponseResult(3005,"更新地址失败，此地址还有关联的订单未收货哦!!");
            }
            addressDao.updateById(address);
            return new ResponseResult(200,"更新地址信息成功");
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseResult(3006,"更新地址信息失败");
        }
    }
}
